﻿/*
   Copyright 2013 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using Flower.Services.Data;
using Flower.StateService;
using System.Data.SqlClient;

namespace Flower.SqlServer.StateService
{
    public class StateStorage : IStateStorage
    {
        private readonly string _connectionString;

        public StateStorage(string connectionStringName)
        {
            ConnectionStringSettings connStrSettings =
                ConfigurationManager.ConnectionStrings[connectionStringName];

            if (connStrSettings == null)
            {
                throw new InvalidOperationException(string.Format("Connection string '{0}' is not found.", connectionStringName));
            }

            _connectionString = connStrSettings.ConnectionString;
        }

        public void Save(StateInfo state)
        {
            using (var connection = new SqlConnection(_connectionString))
            {
                connection.Open();

                using (var cmd = new SqlCommandBuilder(connection))
                {
                    cmd
                        .SetText("dbo.Save")
                        .AddParameter("@Id", state.Id)
                        .AddParameter("@Data", state.Data.Data)
                        .AddParameter("@DataFormat", (int)state.Data.Format)
                        .AddParameter("@Pid", state.Pid)
                        .AddParameter("@ArrivedOn", state.ArrivedOn)
                        .AddParameter("@Flags", (int)state.Flags)
                        .Execute();
                }
            }
        }

        public void Delete(Guid stateId)
        {
            using (var connection = new SqlConnection(_connectionString))
            {
                connection.Open();

                using (var cmd = new SqlCommandBuilder(connection))
                {
                    cmd
                        .SetText("dbo.Delete")
                        .AddParameter("@Id", stateId)
                        .Execute();
                }
            }
        }

        public StateInfo GetLatestState(string pid)
        {
            using (var connection = new SqlConnection(_connectionString))
            {
                connection.Open();

                using (var cmd = new SqlCommandBuilder(connection))
                {
                    return
                        cmd
                            .SetText("dbo.GetLatestState")
                            .AddParameter("@Pid", pid)
                            .ExecuteSingleRow(ReadStateInfo);
                }
            }
        }

        public IEnumerable<StateInfo> GetAllStates()
        {
            using (var connection = new SqlConnection(_connectionString))
            {
                connection.Open();

                using (var cmd = new SqlCommandBuilder(connection))
                {
                    return
                        cmd
                            .SetText("dbo.GetAllStates")
                            .ExecuteReader(ReadStateInfo)
                            .ToList();
                }
            }
        }

        public void UpdateFlags(Guid stateId, StateFlags flags)
        {
            using (var connection = new SqlConnection(_connectionString))
            {
                connection.Open();

                using (var cmd = new SqlCommandBuilder(connection))
                {
                    cmd
                        .SetText("dbo.UpdateFlags")
                        .AddParameter("@Id", stateId)
                        .AddParameter("@Flags", (int)flags)
                        .Execute();
                }
            }
        }

        private static StateInfo ReadStateInfo(SqlDataReader reader)
        {
            return
                new StateInfo 
                {
                    Id = (Guid)reader["Id"],
                    Pid = (string)reader["Pid"],
                    Data = new Blob 
                    {
                        Data = (byte[])reader["Data"],
                        Format = (BlobFormat)(int)reader["DataFormat"]
                    },
                    Flags = (StateFlags)(int)reader["Flags"],
                    ArrivedOn = (DateTime)reader["ArrivedOn"]
                };
        }
    }
}
